import pandas as pd
import matplotlib.pyplot as plt

plt.style.use('ggplot')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

fp_market = './data/601633/holds_info_601633.csv'
fp_price = './data/601633/price_601633.csv'

market = pd.read_csv(fp_market, parse_dates=['day'], index_col='day')
price = pd.read_csv(fp_price, parse_dates=[0], index_col=0)
market = market.merge(price, how='left', left_index=True, right_index=True)
market.fillna(method='ffill', inplace=True)

# share_number 持仓变化率超过ratio
thresh_hold = 0.05
change = market.share_number.pct_change()
change_more = market[change.abs() >= thresh_hold]

market['close'].plot(title='个股北向资金持仓变化',
                     color='k',
                     linewidth=0.5,
                     legend=True)
label_x = market.index[0] + pd.Timedelta('10day')
label_y = market.close[0] * 4
for row in change_more.iterrows():
    ratio = change[row[0]]
    text, face_color = ((f'＋{ratio:,.3f}', 'red') if ratio > 0 else
                        (f'{ratio:,.3f}', 'green'))
    x, y = row[0], row[1].close
    plt.annotate(' ',
                 xy=(x, y),
                 arrowprops=dict(facecolor=face_color, shrink=0.05, width=0.1))
plt.annotate(f'增持超{thresh_hold:,.2%}',
             xy=(label_x, label_y),
             arrowprops=dict(facecolor='red', shrink=0.05, width=0.1))
plt.annotate(f'减持超{thresh_hold:,.2%}',
             xy=(label_x, label_y*1.1),
             arrowprops=dict(facecolor='green', shrink=0.05, width=0.1))
plt.show()
